

** define program to estimate fixed effects

program prepare_FE_interval

	**************
	* identifying fixed effects in pretreatment data only

	set more off
	xtset account_number read_date 

	*1. Estimate fixed effects: note that pretreatment periods do not overlap
	************************
	gen lkWh_using = ldaily
	gen date_using = read_date

	by date_using, sort: egen mean_lkWh = mean(lkWh_using) 
	gen lkWh_demean = lkWh_using - mean_lkWh

	drop mean_lkWh

	drop treatment 
	gen treatment = 1 if read_date >= received_date
	replace treatment=0 if treatment==.

	* compute fixed effects: use all pretreatment data 

	xtreg lkWh_de if treatment ==0, fe
	predict fe, u

	collapse (firstnm) fe* , by(account_number)

	xtile fequantile= fe, nq(5) // quantiles 1-5

	save Data/fixedeffects_interval.dta, replace

end







* estimate household fixed effects 


use Data/Interval_sample.dta, clear

replace contract_start = firstob if contract_start==.
** drop later entrants
drop if contract_start >= td(06Mar2013)

** fixed effects and usage quantiles using only pretreatment data
prepare_FE_interval

merge 1:m account_number using Data/Interval_sample.dta

replace contract_start = firstob if contract_start==.
drop if contract_start >= td(06Mar2013)

drop _merge

rename home_num_people hh_size

* largest hhsize in AER is 6, recode size
replace hh_size=6 if hh_size ==7
** recode number of bedrooms as 4 and above 
replace home_num_bedrooms = 4 if home_num_bedrooms >4 & home_num_bedrooms ~=.

save Data/temp1.dta

collapse (firstnm) hh_size fe home_num_bedrooms, by(account_number)

gen quantile_hhsize=.

forval size = 1(1)6 {
	xtile quantile_hh`size' = fe if hh_size == `size', nq(5)
	replace quantile_hhsize= quantile_hh`size' if hh_size == `size'
	drop quantile_hh`size'
	}
label variable quantile_hhsize "quantiles of usage within hh size"



gen quantile_hhrooms=.

forval size = 1(1)4{
	xtile quantile_hh`size' = fe if home_num_bedrooms == `size', nq(5)
	replace quantile_hhrooms= quantile_hh`size' if home_num_bedrooms == `size'
	drop quantile_hh`size'
	}
label variable quantile_hhrooms "quantiles of usage within hh number of rooms"

merge 1:m account_number using Data/temp1
label variable fequantile "quantiles of pretreatment usage "

by account_number, sort: egen mean_pretreat =   mean(dailykWh) if read_date < received_date
by account_number, sort: egen min_mean = min(mean_pre)
replace mean_pretreat = min_mean
drop min_mean
drop if mean_pre ==.

by account_number, sort: egen days = count(read_date)

drop if days ==1
drop days


save Data/Interval_sample_analysis_robust.dta, replace

erase Data/temp1.dta



